
//
//  XLHostSideTuijianVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/5/28.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLHostSideAliveVC.h"
 
#import "XLHTTPSessionManager.h"
#import "XLHostSideTuijianCell.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLHostSideTuijianModel.h"
#import "XLPersonPageViewController.h"
#import "MJRefresh.h"
#import "NSString+Ext.h"
#import "XLAutoScrollView.h"
#import "XLWebViewController.h"
#import "XLTuijianBannnerListModel.h"
#import "IMAChatViewController.h"

@interface XLHostSideAliveVC ()<UITableViewDataSource,UITableViewDelegate>
{
    XLAutoScrollView *lunbView;//轮播
}
@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,copy  )NSString            *page;
@property (nonatomic,strong) XLHostSideTuijianModel   *HostSideTuijianModel;
@property (nonatomic,strong) UIButton       *charmBtn;
@property (nonatomic,strong) NSMutableArray      *lunboArray;//轮播数组

//记录滑动
@property (nonatomic, assign) float contentOffset;
@property (nonatomic, assign) float oldOffset;
@end

@implementation XLHostSideAliveVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = @"1";
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addTableView];
    [self requrstTalkedPeoplePage];
    [self downloadBannerList];
}

-(void)requrstTalkedPeoplePage
{
    NSDictionary *dic = @{@"pageIndex":_page,
                          @"pageSize":@"16",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"type":@"1"
                          };
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/api/v2/HomePage/GetHomePageList" parameters:dic resultClass:[XLHostSideTuijianModel class]] subscribeNext:^(id x) {
        NSLog(@"美女列表==%@",x);
        [MBProgressHUD hideHUDForView:self.view];
        self.tableView.hidden = NO;
        
        NSArray * listAry = x;
        if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
            [self getJsonArray:listAry];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }else{
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        if (self.modelArray.count == 0) {
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
}

#pragma mark ---下载banner数据
- (void)downloadBannerList{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"Api/v2/HomePage/GetBanners" parameters:@{@"type":@"0"} resultClass:[XLTuijianBannnerListModel class]]subscribeNext:^(id x) {
        if ([x isKindOfClass:[NSNull class]]) {
            return;
        }
        self.lunboArray =(NSMutableArray *)x;
        if (_lunboArray.count > 0) {
            if (lunbView == nil) {
                lunbView = [[XLAutoScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/3)];
                [lunbView changeShowDict:_lunboArray
                               andBlocks:^(NSInteger shopTags) {
                                   if ( shopTags < _lunboArray.count ) {
                                       XLTuijianBannnerListModel *topM = _lunboArray[shopTags];
                                       [self WanNengPush:topM.Url];
                                   }
                               }];
            }
        }
    } error:^(NSError *error) {
        
    }];
}

/**
 *  跳转界面
 */
- (void)WanNengPush:(NSString *)VCName //后台给的vc名字
{
    if ([VCName rangeOfString:@"https://"].location != NSNotFound || [VCName rangeOfString:@"http://"].location != NSNotFound){  //网页链接
        XLWebViewController *vc = [[XLWebViewController alloc] init];
        vc.url = VCName;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSString *class = @"";//XLMyLevelViewController //XLTaskViewController
        if ([VCName rangeOfString:@"activity://"].location != NSNotFound){
            class = [[VCName componentsSeparatedByString:@"//"] lastObject];
        }
        const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
        // 从一个字串返回一个类
        Class newClass = objc_getClass(className);
        if (!newClass)
        {   // 创建一个类
            Class superClass = [NSObject class];
            newClass = objc_allocateClassPair(superClass, className, 0);
            // 注册你创建的这个类
            objc_registerClassPair(newClass);
        }
        // 创建对象
        id instance = [[newClass alloc] init];
        NSDictionary *propertys = @{@"":@""};
        [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            // 检测这个对象是否存在该属性
            if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
                // 利用kvc赋值
                [instance setValue:obj forKey:key];
                [self.navigationController pushViewController:instance animated:YES];
                
            }else{
                [MBProgressHUD showContent:@"敬请期待"];
            }
            
        }];
    }
}

/**
 *  检测对象是否存在该属性
 */
- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance class], &outCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}


- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"1"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.tableView reloadData];
}
#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.page = @"1";
    [self requrstTalkedPeoplePage];
    //[self reshOnlinePeoplesData];
    
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage];
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH-49) style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [_tableView registerClass:[XLHostSideTuijianCell class] forCellReuseIdentifier:NSStringFromClass([XLHostSideTuijianCell class])];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.lunboArray.count > 0)
    {
        if (section == 0) {
            return 1;
        }
    }
    return self.modelArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.lunboArray.count > 0)
    {
        return 2;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.lunboArray.count > 0)
    {
        if (indexPath.section == 0) {
            return (SCREEN_WIDTH-20) * 19 /71 + 18;
        }
    }
    return 86;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.lunboArray.count > 0)
    {
        if (indexPath.section == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bannerCell"];
            if (!cell)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"bannerCell"];
            }
            if (![cell.contentView.subviews containsObject:lunbView]) {
                [cell.contentView addSubview:lunbView];
            }
            return cell;
        }
    }
    
    XLHostSideTuijianCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLHostSideTuijianCell class]) forIndexPath:indexPath];
    XLHostSideTuijianModel *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.headerImageView setImageWithURL:[NSURL URLWithString:model.HeadImg] placeholder:[UIImage imageWithColor:RGB(255, 255, 255)]];
    [cell.levelImage setImageWithURL:[NSURL URLWithString:model.LevelIcon] placeholder:nil];
    cell.time.text = [NSString stringWithFormat:@"%@",model.CreateTime];
    cell.nickNameLabel.text = model.NickName;
    if (cell.nickNameLabel.text.length == 0) {
        cell.nickNameLabel.text = @"      ";
    }
    CGFloat width = [cell.nickNameLabel.text sizeWidthsFont:16 andHeight:20];
    width += 81;//加上头像和排行
    cell.levelImage.frame = CGRectMake(width, 24, 28, 14);
    
#pragma mark --点击 “撩”
    cell.chatButtonClickBlock = ^{
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    chat.isAnchor = @"0";
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
    };
    
//    cell.time.text = model.RechargeTime;
//    cell.stateBgView.backgroundColor = kClearColor;
//    cell.state.textColor = kLightGrayColor;
//    cell.stateBgView.layer.cornerRadius = 0;
//    cell.stateBgView.layer.borderWidth = 0;
//    cell.stateBgView.layer.borderColor = kClearColor.CGColor;
//    if ([model.OnlineStatus isEqualToString:@"3"]) {
//        cell.state.text = @"在线";
//        cell.state.textColor = kDarkGrayColor;
//        cell.stateBgView.layer.cornerRadius = 3;
//        cell.stateBgView.layer.borderWidth = 0.5;
//        cell.stateBgView.layer.borderColor = kLightGrayColor.CGColor;
//    }else{
//        cell.state.text = @"离线";
//        cell.state.textColor = kDarkGrayColor;
//        cell.stateBgView.layer.cornerRadius = 3;
//        cell.stateBgView.layer.borderWidth = 0.5;
//        cell.stateBgView.layer.borderColor = kLightGrayColor.CGColor;
//    }
    cell.chargeMoney.text = [NSString stringWithFormat:@"周消费:%.0f金豆",[model.Recharge floatValue] *10  ];
    cell.time.hidden = YES;
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLHostSideTuijianModel *model = self.modelArray[indexPath.row];
    //跳转私聊界面
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model.UserId)] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    //                    chat.isAnchor = model[@"IsAnchor"];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----判断tableview上滑还是下滑
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.contentOffset = scrollView.contentOffset.y;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat newOffsetY = scrollView.contentOffset.y;
    if (newOffsetY > self.oldOffset && self.oldOffset > self.contentOffset){//上滑
        //写上滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(NO);
        }
    }else if(newOffsetY < self.oldOffset && self.oldOffset < self.contentOffset){//下滑
        //写下滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(YES);
        }
    }
    self.oldOffset = scrollView.contentOffset.y;
}
//记录滑动结束时候的offset
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.oldOffset = scrollView.contentOffset.y;
}


-(void)goChatText:(UIButton *)sender//去主页
{
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"])
    {
        UIButton * chatText = sender;
        self.charmBtn = chatText;
        self.charmBtn.enabled =NO;
        [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:0.5f];//防止重复点击
        XLHostSideTuijianModel *model = self.modelArray[chatText.tag];
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    //                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
        
    }
    
}

-(void)changeButtonStatus{
    self.charmBtn.enabled =YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
